package com.rjkj.medicalwaste.ui.first

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.CodeType
import com.rjkj.medicalwaste.database.getDatabase
import com.rjkj.medicalwaste.databinding.FragmentFirstScanBinding
import com.rjkj.medicalwaste.download.DownLoadProgress
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.repository.GarbageRepository
import com.rjkj.medicalwaste.utils.AppPrefsUtils
import com.rjkj.medicalwaste.utils.BaseConstant
import com.rjkj.medicalwaste.utils.PhoneHelper
import com.rjkj.medicalwaste.viewmodels.FirstScanViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import com.taobao.sophix.SophixManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.regex.Pattern


class FirstScanFragment : BaseFragment<FragmentFirstScanBinding>() {
    val registerForActivityResult =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                lifecycleScope.launch {
                    val updateDevice = userViewModel.updateDevice(
                        PhoneHelper.packageCode(
                            requireContext()
                        ).toString()
                    )
                    if ( updateDevice!= null&&updateDevice.update==1) {
                        val progress = DownLoadProgress(requireContext())
//                        val url = "https://www.rjzhyl.com/cartAPK/phone2/phone2-3.apk"
                        val url = updateDevice.url
                        val fileName = url.split("/").last()
                        progress.showProgress(url, fileName, fileName)
                    }

                }


            }

        }
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private lateinit var startActivity: ActivityResultLauncher<Intent>
    private val viewModel: FirstScanViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        startActivity =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                val resultCode = it.resultCode
                if (resultCode == Activity.RESULT_OK) {
                    val data = it.data?.extras?.getString("codedContent") ?: ""
                    Log.e(TAG, "onCreate: ${resultCode}+${data}")
                    doScanCode(data)
                } else {
                    showTip("扫码失败")
                }
            }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentFirstScanBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        binding.scanData = viewModel
        initKeyEvent()
        return binding.root
    }

    override fun dealCustomScanData(data: String) {
        super.dealCustomScanData(data)
        doScanCode(data)
    }

    override fun onSubscribeUi(binding: FragmentFirstScanBinding) {

        initTip(viewModel)
        lifecycleScope.launchWhenResumed {
            Log.e(TAG, "onSubscribeUi: ", )
            registerForActivityResult.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        binding.title.setOnClickListener {
            SophixManager.getInstance().queryAndLoadNewPatch()
        }
        binding.pic.setOnClickListener {
            scanWithCustomUI()
        }
        binding.tvUser.setOnClickListener {
            scanWithCustomUI()
        }
        binding.tvVersion.setOnClickListener {
//            val uri = Uri.parse("https://www.baidu.com")
            val uri = Uri.parse("https://www.rjzhyl.com/cartAPK/phone2")
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
//            findNavController().navigate(R.id.action_firstScanFragment_to_uploadFragment)
//            requireActivity().updateApp("https://www.rjzhyl.com/cartAPK/phone2/phone2-3.apk",)
        }
        binding.tvVersion.text =
            ("版本号：" + PhoneHelper.packageName(requireContext()) + "." + PhoneHelper.packageCode(
                requireContext()
            ))

        binding.imSetting.setOnClickListener {
            findNavController().navigate(R.id.action_firstScanFragment_to_commonSettingFragment)
        }

        userViewModel.hospitalId.value = AppPrefsUtils.getString(BaseConstant.HOSPITAL_ID)
        userViewModel.hospitalName.value = AppPrefsUtils.getString(BaseConstant.HOSPITAL_NAME)
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                doScanCode(it)
            }
        )

    }

    private fun doScanCode(s: String) {
        Log.e("-", s + "+" + s.length)

        val serial = userViewModel.getSerial()
        if (serial.isNotEmpty() && Pattern.compile("^\\d{15}\$").matcher(serial).matches()) {
            if (s == "forXlbTest") {
                Log.e(TAG, "onSubscribeUi: 111")
                lifecycleScope.launch {
                    GarbageRepository.getInstance(getDatabase(requireContext()).garbageDao)
                        .deleteAllGarbage()
                    viewModel.tips.value = "删除数据！"
                }
//                findNavController().navigate(R.id.action_firstScanFragment_to_xlbTestFragment)
            } else {
                userViewModel.checkLogin(s).observe(viewLifecycleOwner, {
                    checkCode(s).let { type ->
                        if (type == CodeType.Cleaner) {
                            userViewModel.checkLogin(s).observe(viewLifecycleOwner, { user ->
                                if (user != null) {
                                    viewModel.user.value = user.name
                                    viewModel.tips.value = "登录成功！"
                                    userViewModel.cleanerUser = user
                                    lifecycleScope.launch {
                                        delay(250L)
                                        findNavController().navigate(R.id.action_firstScanFragment_to_homeFragment)
                                    }
                                } else {
                                    viewModel.user.value = ""
                                    viewModel.tips.value = "未查询到该用户！"
                                }
                            })
                        } else {
                            showTip("请勿扫描${type.alias}")
                        }
                    }

                })

            }
        } else {
            showTip("设备号有误")
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy: ")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.e(TAG, "onDestroyView: ")
        viewModel.user.value = ""
    }

    override fun onDetach() {
        super.onDetach()
        Log.e(TAG, "onDetach: ")
    }
}